import { Spin, message, notification } from "antd";
import { ControlType as TYPE } from "@components";
import { useRef, useState } from "react";
import { getAddressFindRegion } from "@apis/indexApi";
import { riskAreaAdd, riskAreaEdit } from "@apis/riskAreaApi";
import { session } from '@core'
import { RULE_REQUIRED } from "@rules";

let map = null

const setProvinceListFun = async (parmas, setValue, setLoading) => {
  let codeKey, nameKey = ''
  switch (parmas.type) {
    case 'province':
      codeKey = 'provinceCode'
      nameKey = 'provinceName'
      break;
    case 'city':
      codeKey = 'cityCode'
      nameKey = 'cityName'
      break;
    case 'county':
      codeKey = 'countyCode'
      nameKey = 'countyName'
      break;
    default:
      break;
  }

  setValue([])
  setLoading(true)
  const {data, error} = await getAddressFindRegion(parmas)
  if (error) return

  let list = []
  for (const item of data) {
    const { [codeKey]: value, [nameKey]: label } = item
    list.push({ value, label })
  }
  setValue(list)
  setLoading(false)

}

const getSelectText = (list, value) => {
  const listItem = list.find(item => item.value === value)
  return listItem.label
}

export const useDistrictConfig = (setLoading, onCancel) => {
  const formRef = useRef('district');

  const [labelLoading, setLabelLoading] = useState(false)

  const [provinceList, setProvinceList] = useState([])
  const [cityList, setCityList] = useState([])
  const [countyList, setCountyList] = useState([])

  const selectConfig = {
    controlType: TYPE.SELECT,
    allowClear: true,
    showSearch: true,
    optionFilterProp: "children",
    filterOption: (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
    notFoundContent: labelLoading ? <Spin size="small" /> : null,
  }

  // children
  const fields = [
    { name: "cfgAreaName", label: "区域名称", controlType: TYPE.INPUT, rules: [RULE_REQUIRED] },
    { name: 'unitCode', label: "归属机构", controlType: TYPE.SELECT, codeKey: 'userAuthUnits', ...selectConfig, rules: [RULE_REQUIRED] },
    { 
      name: 'provinceCode', label: '所在省', options: provinceList, ...selectConfig, rules: [RULE_REQUIRED],
      onSelect: (value, option) => {
        if (!option?.value) return
        formRef.current.setFieldsValue({ ...formRef.current.getFieldValue(), cityCode: null, countyCode: null })
        setCityList([])
        setCountyList([])

        getBoundary(option.children)
      },
      onFocus: () => {
        if (provinceList.length) return
        const parmas = { type: "province", code: "" }
        setProvinceListFun(parmas, setProvinceList, setLabelLoading)
      }
    },
    { 
      name: 'cityCode', label: '所在市', options: cityList, ...selectConfig,
      onSelect: (value, option) => {
        if (!option?.value) return
        formRef.current.setFieldsValue({ ...formRef.current.getFieldValue(), countyCode: null })
        setCountyList([])

        const province = getSelectText(provinceList, formRef.current.getFieldValue('provinceCode'))
        const address = province + option.children
        getBoundary(address)
      },
      onFocus: () => {
        const code = formRef.current.getFieldValue('provinceCode')
        if (!code) return message.error('请先选择省份')
 
        const parmas = { type: "city", code  }
        setProvinceListFun(parmas, setCityList, setLabelLoading)
      }
    },
    { 
      name: 'countyCode', label: '所在区', options: countyList, ...selectConfig,
      onSelect: (value, option) => {
        if (!option?.value) return
        const province = getSelectText(provinceList, formRef.current.getFieldValue('provinceCode'))
        const city = getSelectText(cityList, formRef.current.getFieldValue('cityCode'))
        const address = province + city + option.children
        getBoundary(address)
      },
      onFocus: () => {
        const code = formRef.current.getFieldValue('cityCode')
        if (!code) return message.error('请先选择城市')
        const parmas = { type: "county", code }
        setProvinceListFun(parmas, setCountyList, setLabelLoading)
      }
    }
  ];

  const onFinish = async (formData) => {
    let fetch = riskAreaAdd
    if (session.get('cfgAreaId')) {
      fetch = riskAreaEdit
    }
    setLoading(true)
    const params = {
      cfgAreaId: session.get('cfgAreaId'),
      ...formData,
      areaType: 'district',
    }
    const {data, error} = await fetch(params)
    setLoading(false)
    if (error) return
    message.success(data)
    onCancel(true)
  }
  
  const formProps = {
    name: "district",
    formRef,
    fields,
    onFinish,
    onCancel: () => onCancel(),
    submitButton: {
      show: true,
      icon: "SaveOutlined",
      label: "保存",
    },
    resetButton: { show: true, label: "关闭" },
    layoutProps: {
      layout: "grid",
      gridConfig: { colCount: 6 },
    },
    isButtonLineFeed: false,
  };

  const checkBMapGL = () => {
    try { // 检测 BMapGL 是否存在
      new BMapGL.Geocoder()
      return false
    } catch (error) {
      console.error(error);
      notification.error({
        message: '温馨提醒',
        description: '地图加载失败，请检查网络或尝试刷新页面',
        placement: 'top',
      })
      return true
    }
  }

  const initMap = () => {
    if (checkBMapGL()) return
    
    map = new BMapGL.Map('riskAreaContainer'); // 创建Map实例
    map.centerAndZoom(new BMapGL.Point(105.8614, 37.362), 6); // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true); //启用地图滚轮放大缩小
    map.disableDoubleClickZoom(); //	取消地图双击缩放
    map.setMinZoom(6);
  }

  const getBoundary = (address) => { 
    if (checkBMapGL()) return

    setLoading(true)
    const bdary = new BMapGL.Boundary();
    bdary.get(address, function(rs){//获取行政区域
      setBoundary(rs.boundaries)
    });   
  }

  const setBoundary = (boundaries) => { // 此方法用于自定义区域
    map.clearOverlays(); //清除地图覆盖物       
    if (!boundaries.length) return
    const Polygon = new BMapGL.Polygon(boundaries, {
      strokeWeight: 2,
      strokeColor: "#3072f6",
      fillColor: "#3072f6",
      fillOpacity: 0.2,
    });
    map.addOverlay(Polygon);
    const newPath = []
    Polygon.getPath().forEach(item => {
      if (Array.isArray(item)) {
        newPath.push(...item)
        return
      }
      newPath.push(item)
    })
    map.setViewport(newPath); //调整视野      
    setLoading(false)
  }

  return {
    formRef,
    formProps,
    initMap,
    getBoundary,
    setProvinceListFun,
    setLabelLoading,
    setProvinceList,
    setCityList,
    setCountyList,
  }

}

